package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class UserPaidAlbumStrategy implements UpdateUserPaidRecordStrategy {

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper ;

    @Transactional
    @Override
    public void updateUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {

        /**
         * 为了防止消息重复消费所带来的问题，该接口方法需要考虑接口的幂等性
         * 方案一：根据订单编号从数据库中查询数据，如果可以查询到数据就说明重复消费了，就不需要再次进行保存了
         * 方案二：给orderNo列添加唯一索引，当第二次保存数据的时候，数据库直接报错
         */
        LambdaQueryWrapper<UserPaidAlbum> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserPaidAlbum::getOrderNo , userPaidRecordVo.getOrderNo());
        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(lambdaQueryWrapper);
        if(userPaidAlbum != null) {
            return  ;
        }

        // 保存专辑购买的交易信息
        userPaidAlbum = new UserPaidAlbum() ;
        userPaidAlbum.setOrderNo(userPaidRecordVo.getOrderNo());
        userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
        userPaidAlbum.setAlbumId(userPaidRecordVo.getItemIdList().get(0));
        userPaidAlbumMapper.insert(userPaidAlbum) ;

    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_ALBUM;
    }
}